package com.study.blogsearchproducer.config;


import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * Es 连接配置
 *
 * @author yana
 */
@Configuration
public class EsClientConfig {

    private String hostname = "127.0.0.1";

    private int port = 9200;

    private volatile RestClientBuilder restClientBuilder;

    /**
     * 手动创建restClient的bean,手动build将hostname注入到内存的list去，
     * 否则由于hostname取的本地，在spring做健康检查时，会连本地的9200，导致健康检查失败
     *
     * @return
     */
    @Bean
    public RestClient restClient() {
        restClientBuilder = RestClient.builder(new HttpHost(hostname, port, HttpHost.DEFAULT_SCHEME_NAME));
        return restClientBuilder.build();
    }

    @Bean
    @DependsOn("restClient")
    public RestHighLevelClient rhlClient() {
        // 如果有多个从节点可以持续在内部new多个HttpHost，参数1是IP，参数2是端口，参数3是通信协议
        return new RestHighLevelClient(restClientBuilder);
    }

}
